package com.xiaomaoguai.security.browser;

import com.xiaomaoguai.security.core.properties.MySecurityProperties;
import com.xiaomaoguai.security.support.SimpleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @fileName: BrowserSecurityController.java
 * @author: WeiHui-Z
 * @date: 2017/11/29 11:27
 * @version: v1.0.0
 */
@RestController
public class BrowserSecurityController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BrowserSecurityController.class);

    private final RequestCache requestCache = new HttpSessionRequestCache();

    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Resource
    private MySecurityProperties mySecurityProperties;

    @RequestMapping("/authentication/require")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String redirectUrl = savedRequest.getRedirectUrl();
        LOGGER.info("引发跳转的URL:{}", redirectUrl);
        if (StringUtils.endsWithIgnoreCase(redirectUrl, ".html")) {
            redirectStrategy.sendRedirect(request, response, mySecurityProperties.getBrowser().getLoginPage());
        }
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登陆页。");
    }
}
